<template>
  <div>
    <m-infinite
      v-model="loading"
      :isFinished="finished"
      @onLoad="getPexelsList"
    >
      <m-waterfall
        class="w-full px-1"
        :data="pexelsList"
        :column="isMobileTerminal ? 2 : 5"
        nodeKey="id"
        :picturePreReading="false"
      >
        <template #default="{ item, width }">
          <item-vue :data="item" :width="width" @click="changeRoute"></item-vue>
        </template>
      </m-waterfall>
    </m-infinite>
    <transition
      :css="false"
      @before-enter="beforeEnter"
      @enter="enter"
      @leave="leave"
    >
      <pins-vue v-if="isVsiablePins" :id="pinsInfo.id"></pins-vue>
    </transition>
  </div>
</template>
<script setup>
import { ref, watch } from 'vue'
import { getPexels } from '@/api/pexels'
import itemVue from './item.vue'
import { isMobileTerminal } from '@/utils/flexible'
import { useStore } from 'vuex'
import pinsVue from '../../../pins/components/pins.vue'
import gsap from 'gsap'
import { useEventListener } from '@vueuse/core'
const store = useStore()
let query = {
  page: 1,
  size: 20
}
const finished = ref(false)
const loading = ref(false)
const pexelsList = ref([])
const getPexelsList = async (keyword) => {
  if (finished.value) return
  loading.value = true
  const params = {
    ...query,
    searchText: keyword
  }
  const res = await getPexels(params)
  pexelsList.value.push(...res.list)
  query.page += 1
  if (pexelsList.value.length === res.total) {
    finished.value = true
  }
  loading.value = false
}
getPexelsList()
// 控制图片详情展示
const isVsiablePins = ref(false)
const pinsInfo = ref({})

const changeRoute = (item) => {
  history.pushState(null, null, `/pinks/${item.id}`)
  isVsiablePins.value = true
  pinsInfo.value = item
}
const leave = (el, done) => {
  gsap.to(el, {
    scaleX: 0,
    scaleY: 0,
    translateX: pinsInfo.value.location?.translateX,
    translateY: pinsInfo.value.location?.translateY,
    opacity: 0,
    onComplete: done
  })
}
const enter = (el, done) => {
  gsap.to(el, {
    duration: 0.5,
    scaleX: 1,
    scaleY: 1,
    translateX: 0,
    translateY: 0,
    opacity: 1,
    onComplete: done
  })
}
const beforeEnter = (el) => {
  gsap.set(el, {
    scaleX: 0,
    scaleY: 0,
    transformOrigin: '0 0',
    translateX: pinsInfo.value.location?.translateX,
    translateY: pinsInfo.value.location?.translateY,
    opacity: 0
  })
}
useEventListener(window, 'popstate', () => {
  isVsiablePins.value = false
})
watch(
  () => store.getters.searchText,
  (newVal) => {
    pexelsList.value = []
    query.page = 1
    getPexelsList(newVal)
  },
  {
    immediate: true
  }
)
</script>
<style lang="scss" scoped></style>
